import { join } from 'path'
import { existsSync, readFileSync } from 'fs'
import { parse } from 'dotenv'
import chalk from 'chalk'
import { createLogger } from '../logger'
import { Generator } from './generator'

const cwd = process.cwd()
const envPath = join(cwd, '.env')
const logger = createLogger('info', { prefix: '[Gen api]' })

if (!existsSync(envPath)) {
  logger.error(chalk.red(`在 ${cwd} 中未找到名为 .env 的文件`))
  process.exit(1)
}

const {
  EF_API_PREFIX,
  VUE_APP_API_PREFIX,
  VITE_API_PREFIX,
  TARO_API_PREFIX,
} = parse(readFileSync(join(cwd, '.env')))

if (!EF_API_PREFIX && !VUE_APP_API_PREFIX && !VITE_API_PREFIX && !TARO_API_PREFIX) {
  logger.warn(chalk.yellow('未找到名为 EF_API_PREFIX 、TARO_API_PREFIX、VUE_APP_API_PREFIX 或 VITE_API_PREFIX 的变量，默认当做空字符串处理'))
}

const prefix = TARO_API_PREFIX ? TARO_API_PREFIX : EF_API_PREFIX ? EF_API_PREFIX : VITE_API_PREFIX ? VITE_API_PREFIX : VUE_APP_API_PREFIX ? VUE_APP_API_PREFIX : ''

export const run = (type: string, token: string, host: string) => {
  const generator = new Generator(host, token, prefix || '', type)
  generator.generate()
}
